package com.tx.activemq._01_c_p._04_jms_dependence._043_acknowledge;

import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;
import java.io.IOException;

/**
 * 事务
 */
public class Consumer {

    private static final String DEFAULT_URL = "tcp://192.168.254.30:61616";

    private static final String QUEUE_NAME = "queue_01";

    public static void main(String[] args) throws JMSException, IOException {
        System.out.println("****1号消费者***");
        ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(DEFAULT_URL);
        Connection connection = factory.createConnection();
        connection.start();

        Session session = connection.createSession(true, Session.CLIENT_ACKNOWLEDGE);
        Queue queue = session.createQueue(QUEUE_NAME);
        MessageConsumer consumer = session.createConsumer(queue);

        consumer.setMessageListener(msg ->{
            if(msg != null && msg instanceof TextMessage){
                TextMessage textMessage = (TextMessage)msg;
                try {
                    System.out.println("textMsg:" + textMessage.getText());
                    textMessage.acknowledge();
                    //消费者开启事务，必commit
                    session.commit();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });



        //挂起控制台
        System.in.read();

        consumer.close();
        session.close();
        connection.close();
    }
}